import numpy as np
import pylab as pl
import sys, os

sys.path.append('src/')
import transceiver
import misc

def write_data(x,y,fname,xname='x',yname='y'):
    lw = []
    lw += [xname+' '+yname+'\r\n']
    for i0,j0 in enumerate(y):
        if isinstance(x[i0], str)==True:
            lw += [x[i0]+' '+`j0`+'\r\n']
        else:
            lw += [`x[i0]`+' '+`j0`+'\r\n']

    open('tex/data/'+fname+'.txt','wb').writelines(lw)



""" PAPR Simulation: """

fftlen = 1024
Fs = fftlen/(1./15000)

RB = 50
CP = True
modsym = 7
reps = 100

bb = transceiver.Baseband(RB,fftlen)
cc = misc.Calc()

xpapr = []
xpapr1 = []
xpapr2 = []
xpapr3 = []
for i in range(reps):
    x16qam = np.random.randint(0,2,48*RB*modsym)
    xqpsk = np.random.randint(0,2,24*RB*modsym)

    xcp_all = bb.ofdm(x16qam,modsym,CP,'16QAM')
    xcp_all1 = bb.sc_fdm(x16qam,modsym,CP,'16QAM')
    
    xcp_all2 = bb.ofdm(xqpsk,modsym,CP,'QPSK')
    xcp_all3 = bb.sc_fdm(xqpsk,modsym,CP,'QPSK')
 
    xpapr += [cc.PAPR(xcp_all)]
    xpapr1 += [cc.PAPR(xcp_all1)]

    xpapr2 += [cc.PAPR(xcp_all2)]
    xpapr3 += [cc.PAPR(xcp_all3)]



xdbm,xyh = cc.CCDF(xpapr,1000)
xdbm1,xyh1 = cc.CCDF(xpapr1,1000)
xdbm2,xyh2 = cc.CCDF(xpapr2,1000)
xdbm3,xyh3 = cc.CCDF(xpapr3,1000)


write_data(xyh,xdbm,'papr_16q_o')
write_data(xyh1,xdbm1,'papr_16q_s')
write_data(xyh2,xdbm2,'papr_qpsk_o')
write_data(xyh3,xdbm3,'papr_qpsk_s')


pl.figure(2)
pl.semilogy(xyh,xdbm,'r')
pl.semilogy(xyh1,xdbm1,'b')
pl.semilogy(xyh2,xdbm2,'k')
pl.semilogy(xyh3,xdbm3,'g')
pl.show()

